<template>
  <div class="search-container">
    <!-- 搜索页面 -->
    <form action="/" class="search-from">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>

    <!-- 搜索结果 -->
    <SearchResult v-if="isResultShow" :searchText="searchText"></SearchResult>
    <!-- 搜索结果 -->

    <!-- 联想建议 -->
    <SearchSuggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></SearchSuggestion>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <SearchHistoryVue
      v-else
      :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
    ></SearchHistoryVue>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistoryVue from "./components/search-history.vue";
import SearchSuggestion from "./components/search-suggestion.vue";
import SearchResult from "./components/search-result.vue";
import { getItem, setItem } from "@/utils/storage";

export default {
  name: "SearchIndex",
  components: {
    SearchHistoryVue,
    SearchSuggestion,
    SearchResult,
  },
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories: getItem("TOUTIAO_SEARCH_HISTORIES") || [],
    };
  },
  methods: {
    // 获取输入的值
    onSearch(val) {
      this.searchText = val;
      this.isResultShow = true;

      // 通过输入的值判断数组内有没有 有的话 拿到对应的索引
      const index = this.searchHistories.indexOf(val);
      // 判断 数组内 包含的话 就删除
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }
      // 在 数组开头添加
      this.searchHistories.unshift(val);
    },
    // 点击取消触发
    onCancel() {
      this.$router.back();
    },
  },
  // 数据持久化
  watch: {
    searchHistories(value) {
      setItem("TOUTIAO_SEARCH_HISTORIES", value);
    },
  },
};
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-from {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1;
  }
}
</style>
